import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';
import actions from './actions';
import mutations from './mutations';
import pagesA from './modules/pagesA';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    token: null, // 登录令牌
    userInfo: null, // 用户信息
    vuexData: {
      desc: '这里的数据只存储在 vuex 中, 并没有缓存到 localStorage',
    },
  },
  getters: {
    isLogin: (state) => !!state.token,
    isVip: (state) => state.userInfo?.level === 1,
  },
  mutations,
  actions,
  modules: {
    pagesA,
  },
  plugins: [
    createPersistedState({
      key: 'vue_uniapp_view_vuex', // 存储 key
      // storage: window.localStorage, // 可选 sessionStorage
      storage: {
        getItem: (key) => uni.getStorageSync(key),
        setItem: (key, value) => uni.setStorageSync(key, value),
        removeItem: (key) => uni.removeStorageSync(key),
      },
      // paths: ['token', 'userInfo', 'pagesA.count'],
      reducer(val) {
        return {
          token: val.token,
          userInfo: val.userInfo,
          pagesA: { count: val.pagesA.count },
        };
      }, // 指定需要缓存的状态
    }),
  ],
});
